<template>
  <el-container class="order-detail">
    <el-main>
      <div class="warm-tip sa-m-b-16">
        温馨提示
        <br />1、如果无法发货，请及时与买家联系并说明情况后主动退款；
        <br />2、买家申请售后，须征得买家同意后发货，否则买家有权拒收货物；
        <br />3、订单全部退款将会退回商品库存，并且减少实际销量，订单商品上的主动退款不会退回库存和销量
      </div>
      <div class="status-content sa-m-b-16">
        <el-row :gutter="10">
          <el-col class="sa-col-12 left" :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
            <div class="name sa-flex sa-m-b-4">
              <el-icon class="refresh sa-m-r-4" @click="getOrderDetail"><RefreshLeft /></el-icon>
              {{ state.orderDetail.status_text }}
            </div>
            <div class="desc sa-m-b-16">
              {{ state.orderDetail.status_desc }}
            </div>
            <div class="tools sa-m-b-4">
              <template v-if="state.orderDetail.btns">
                <el-button
                  v-if="state.orderDetail.btns.includes('send')"
                  v-auth="'shop.admin.order.order.dispatch'"
                  type="primary"
                  @click="onOpenDispatch"
                  >立即发货</el-button
                >
                <el-button
                  v-if="state.orderDetail.btns.includes('refund')"
                  v-auth="'shop.admin.order.order.fullrefund'"
                  @click="onOpenRefund"
                  >全部退款</el-button
                >
              </template>
            </div>
            <div class="memo sa-flex">
              <template v-if="memoForm.flag">
                <el-input class="sa-w-120 sa-m-r-12" v-model="memoForm.data" size="small" />
                <el-button class="is-link" type="primary" size="small" @click="onConfirmMemo"
                  >确定</el-button
                >
                <el-button
                  class="is-link"
                  type="primary"
                  size="small"
                  @click="memoForm.flag = false"
                  >取消</el-button
                >
              </template>
              <!-- TODO：这里没有权限的时候有问题 -->
              <template v-if="!memoForm.flag">
                <div v-if="state.orderDetail.memo" class="sa-m-r-12">
                  {{ state.orderDetail.memo }}
                </div>
                <el-button
                  v-auth="'shop.admin.order.order.editmemo'"
                  class="is-link"
                  type="primary"
                  size="small"
                  @click="onChangeMemoFlag(state.orderDetail.memo)"
                  >{{ state.orderDetail.memo ? '修改' : '添加' }}备注</el-button
                >
              </template>
            </div>
          </el-col>
          <el-col class="sa-col-24 center" :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <status-steps :orderDetail="state.orderDetail" />
          </el-col>
          <el-col class="sa-col-12 right" :xs="12" :sm="12" :md="6" :lg="6" :xl="6">
            <div class="right-item">
              <div class="label">商品总价：</div>
              <div class="content">¥{{ state.orderDetail.goods_amount }}</div>
            </div>
            <div class="right-item">
              <div class="label">运费价格：</div>
              <div class="content"> ¥{{ state.orderDetail.dispatch_amount }} </div>
            </div>
            <div
              class="right-item right-item-discount"
              v-if="
                state.orderDetail.ext &&
                (state.orderDetail.ext.promo_infos ||
                state.orderDetail.coupon_id)
              "
            >
              <div class="label">活动优惠：</div>
              <div class="content">
                <div
                  class="sa-flex sa-m-b-12"
                  v-if="Number(state.orderDetail.ext.promo_discounts.full_reduce) > 0"
                >
                  <div class="label">满减</div>
                  <div class="content sa-m-l-12">
                    -¥{{ state.orderDetail.ext.promo_discounts.full_reduce }}
                  </div>
                </div>
                <div
                  class="sa-flex sa-m-b-12"
                  v-if="Number(state.orderDetail.ext.promo_discounts.full_discount) > 0"
                >
                  <div class="label">满折</div>
                  <div class="content sa-m-l-12">
                    -¥{{ state.orderDetail.ext.promo_discounts.full_discount }}
                  </div>
                </div>
                <div
                  class="sa-flex sa-m-b-12"
                  v-if="Number(state.orderDetail.ext.promo_discounts.full_gift) > 0"
                >
                  <div class="label">满赠</div>
                  <div class="content sa-m-l-12"></div>
                </div>
                <div
                  class="sa-flex sa-m-b-12"
                  v-if="Number(state.orderDetail.ext.promo_discounts.free_shipping) > 0"
                >
                  <div class="label">满包邮</div>
                  <div class="content sa-m-l-12">
                    -¥{{ state.orderDetail.ext.promo_discounts.free_shipping }}
                  </div>
                </div>
                <div v-if="state.orderDetail.coupon_id" class="right-item">
                  <div class="label">优惠券</div>
                  <div class="content sa-m-l-12">
                    -¥{{ state.orderDetail.coupon_discount_fee }}
                  </div>
                </div>
              </div>
            </div>
            <div class="right-item">
              <div class="label">
                {{['paid', 'completed'].includes(state.orderDetail.status)?'实付金额':'应付金额'}}：
              </div>
              <div class="content fee-content sa-flex">
                ¥{{ state.orderDetail.pay_fee }}
                <s
                  v-if="state.orderDetail.pay_fee != state.orderDetail.original_pay_fee"
                  class="original-pay-fee sa-m-l-4"
                >
                  {{ state.orderDetail.original_pay_fee }}
                </s>
                <el-button
                  v-if="state.orderDetail.btns && state.orderDetail.btns.includes('change_fee')"
                  v-auth="'shop.admin.order.order.changefee'"
                  class="is-link sa-m-l-8"
                  type="primary"
                  size="small"
                  @click="onChangeFee"
                  >改价</el-button
                >
              </div>
            </div>
          </el-col>
        </el-row>
        <div class="remark right-item">
          <div class="label">买家留言：</div>
          <div class="content">
            {{ state.orderDetail.remark || '暂无留言' }}
          </div>
        </div>
      </div>

      <!-- tabs内容 -->
      <div class="tabs-content sa-m-b-16">
        <el-tabs v-model="state.orderTabs" @tab-change="state.changeExpressStatus = false">
          <el-tab-pane label="订单信息" name="1">
            <el-row class="order-content" :gutter="10">
              <el-col class="sa-col-12" :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
                <div class="title">交易信息</div>
                <div class="item">
                  <div class="label">订单编号：</div>
                  <div class="content">
                    {{ state.orderDetail.order_sn }}
                    <sa-svg
                      class="copy sa-m-l-4 cursor-pointer"
                      name="sa-copy"
                      @click="useClip(state.orderDetail.order_sn)"
                    ></sa-svg>
                  </div>
                </div>
                <div class="item">
                  <div class="label">订单来源：</div>
                  <div class="content">
                    {{ state.orderDetail.platform }}
                  </div>
                </div>
                <div class="item" v-if="state.orderDetail.paid_time">
                  <div class="label">付款时间：</div>
                  <div class="content">{{ state.orderDetail.paid_time }}</div>
                </div>
              </el-col>
              <el-col
                v-if="state.orderDetail.user"
                class="sa-col-12"
                :xs="24"
                :sm="24"
                :md="12"
                :lg="6"
                :xl="6"
              >
                <div class="title">买家信息</div>
                <div class="item">
                  <div class="label">用户昵称：</div>
                  <div class="content sa-flex">
                    <sa-user-profile
                      :user="state.orderDetail.user"
                      :id="state.orderDetail.user_id"
                      :isAvatar="false"
                    />
                  </div>
                </div>
              </el-col>
              <el-col
                v-if="state.orderDetail.address"
                class="sa-col-12"
                :xs="24"
                :sm="24"
                :md="12"
                :lg="6"
                :xl="6"
              >
                <div class="title sa-flex">
                  收货信息
                  <template v-if="state.orderDetail?.btns.includes('edit_consignee')">
                    <template v-if="!state.editConsigneeFlag">
                      <el-button
                        v-auth="'shop.admin.order.order.editconsignee'"
                        class="is-link sa-m-l-12"
                        type="primary"
                        size="small"
                        @click="onChangeEditConsigneeFlag(true)"
                        >修改</el-button
                      >
                      <el-button
                        class="is-link sa-m-l-8"
                        type="success"
                        size="small"
                        @click="
                          useClip(
                            `收货昵称：${state.orderDetail.address.consignee};联系方式：${state.orderDetail.address.mobile};
                          收货地址：${state.orderDetail.address.province_name}${state.orderDetail.address.city_name}${state.orderDetail.address.district_name}${state.orderDetail.address.address}`,
                          )
                        "
                        >复制</el-button
                      >
                    </template>
                    <template v-if="state.editConsigneeFlag">
                      <el-button
                        class="is-link sa-m-l-12"
                        type="danger"
                        size="small"
                        @click="state.editConsigneeFlag = false"
                      >
                        取消
                      </el-button>
                      <el-button
                        class="is-link sa-m-l-8"
                        type="primary"
                        size="small"
                        @click="onEditConsignee()"
                        >确定</el-button
                      >
                    </template>
                  </template>
                </div>
                <div class="item">
                  <div class="label">收货昵称：</div>
                  <div class="content">
                    <span v-if="!state.editConsigneeFlag">
                      {{ state.orderDetail.address.consignee }}
                    </span>
                    <el-input
                      v-if="state.editConsigneeFlag"
                      v-model="state.address.consignee"
                      size="small"
                    ></el-input>
                  </div>
                </div>
                <div class="item">
                  <div class="label">联系方式：</div>
                  <div class="content">
                    <span v-if="!state.editConsigneeFlag">
                      {{ state.orderDetail.address.mobile }}
                    </span>
                    <el-input
                      v-if="state.editConsigneeFlag"
                      v-model="state.address.mobile"
                      size="small"
                    ></el-input>
                  </div>
                </div>
                <div class="item">
                  <div class="label">收货地址：</div>
                  <div class="content">
                    <div class="sa-m-b-4" v-if="!state.editConsigneeFlag">
                      {{ state.orderDetail.address.province_name }}&nbsp;
                      {{ state.orderDetail.address.city_name }}&nbsp;
                      {{ state.orderDetail.address.district_name }}
                    </div>
                    <el-cascader
                      v-if="state.editConsigneeFlag"
                      class="sa-m-b-4"
                      ref="addressRef"
                      v-model="state.address.pcd"
                      :options="state.area"
                      :props="{ label: 'name', value: 'id' }"
                      size="small"
                    />
                    <div v-if="!state.editConsigneeFlag">
                      {{ state.orderDetail.address.address }}
                    </div>
                    <el-input
                      v-if="state.editConsigneeFlag"
                      v-model="state.address.address"
                      size="small"
                    ></el-input>
                  </div>
                </div>
              </el-col>
              <el-col
                v-if="state.orderDetail.invoice_status == 1"
                class="sa-col-12"
                :xs="24"
                :sm="24"
                :md="12"
                :lg="6"
                :xl="6"
              >
                <div class="title sa-flex">
                  发票信息
                  <div class="sa-m-l-12">
                    <span
                      v-if="state.orderDetail.invoice.status != 'waiting'"
                      class="invoice-status"
                      >{{ state.orderDetail.invoice.status_text }}</span
                    >
                    <el-button
                      v-if="state.orderDetail.invoice.status == 'waiting'"
                      class="is-link"
                      type="primary"
                      text
                      size="small"
                      @click="onChangeInvoiceStatus(state.orderDetail.invoice)"
                      >确认开具</el-button
                    >
                  </div>
                </div>
                <div class="item">
                  <div class="label">发票类型：</div>
                  <div class="content">
                    {{ state.orderDetail.invoice.type_text }}
                  </div>
                </div>
                <div class="item">
                  <div class="label">抬头名称：</div>
                  <div class="content">
                    {{ state.orderDetail.invoice.name }}
                  </div>
                </div>
                <div class="item" v-if="state.orderDetail.invoice.type === 'company'">
                  <div class="label">税号：</div>
                  <div class="content">
                    {{ state.orderDetail.invoice.tax_no }}
                  </div>
                </div>
                <div class="item">
                  <div class="label">手机号：</div>
                  <div class="content">
                    {{ state.orderDetail.invoice.mobile }}
                  </div>
                </div>
                <div class="item">
                  <div class="label">金额：</div>
                  <div class="content"> ￥{{ state.orderDetail.invoice.amount }} </div>
                </div>
                <div class="item" v-if="state.orderDetail.invoice.status === 'finish'">
                  <div class="label">实际开票金额：</div>
                  <div class="content"> ￥{{ state.orderDetail.invoice.invoice_amount }} </div>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane
            :label="`包裹${exindex + 1}`"
            v-for="(ex, exindex) in state.orderDetail.express"
            :key="ex"
            :name="`${exindex + 2}`"
          >
            <el-row class="express-content" :gutter="10">
              <el-col class="sa-col-8 left" :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
                <div class="title sa-flex">
                  物流信息
                  <div class="sa-flex sa-m-l-12">
                    <!-- 运单信息 -->
                    <template v-if="!state.changeExpressStatus">
                      <el-button
                        v-auth="'shop.admin.order.order.dispatch'"
                        class="is-link"
                        type="primary"
                        size="small"
                        @click="onChangeExpressStatus(ex)"
                        >修改运单</el-button
                      >
                      <el-popconfirm
                        width="fit-content"
                        confirm-button-text="确认"
                        cancel-button-text="取消"
                        title="您确定要取消运单吗？"
                        @confirm="onCancelExpress(ex.id)"
                      >
                        <template #reference>
                          <el-button
                            v-auth="'shop.admin.order.order.dispatch'"
                            class="is-link sa-m-l-8"
                            type="danger"
                            size="small"
                            @click="cancelExpressPopover = true"
                          >
                            取消运单
                          </el-button>
                        </template>
                      </el-popconfirm>
                    </template>
                    <!-- 修改运单信息 -->
                    <template v-else>
                      <el-button
                        class="is-link"
                        type="danger"
                        size="small"
                        @click="state.changeExpressStatus = false"
                      >
                        取消
                      </el-button>
                      <el-button
                        class="is-link sa-m-l-8"
                        type="primary"
                        size="small"
                        @click="onConfirmExpress(ex.id)"
                        >确认</el-button
                      >
                    </template>
                  </div>
                </div>
                <div class="item">
                  <div class="label">快递公司：</div>
                  <div class="content">
                    <div v-if="!state.changeExpressStatus">
                      {{ ex.express_name }}
                    </div>
                    <el-select
                      size="small"
                      v-if="state.changeExpressStatus"
                      v-model="express.code"
                      placeholder="请选择快递公司"
                      @change="onChangeExpressCode"
                      filterable
                      remote
                      reserve-keyword
                      :remote-method="remoteMethod"
                      :loading="deliverCompany.loading"
                    >
                      <el-option
                        v-for="dc in deliverCompany.data"
                        :key="dc"
                        :label="dc.name"
                        :value="dc.code"
                        :ref="`dc-${dc.code}`"
                        :data-name="dc.name"
                        >{{ dc.name }}&nbsp;({{ dc.code }})</el-option
                      >
                      <div class="sa-p-l-15 sa-p-r-27">
                        <sa-pagination
                          layout="total, prev, pager, next"
                          :pageData="deliverCompany.pageData"
                          @updateFn="getDeliverCompany"
                        />
                      </div>
                    </el-select>
                  </div>
                </div>
                <div class="item">
                  <div class="label">快递单号：</div>
                  <div class="content">
                    <div v-if="!state.changeExpressStatus">
                      {{ ex.express_no }}
                    </div>
                    <el-input
                      size="small"
                      v-if="state.changeExpressStatus"
                      v-model="express.no"
                    ></el-input>
                  </div>
                </div>
                <div class="goods-item sa-flex sa-m-t-12" v-for="goods in ex.items" :key="goods">
                  <sa-image :url="goods.goods_image" size="40"></sa-image>
                  <div class="sa-m-l-8">
                    <div class="goods-title sa-table-line-1 sa-m-b-4">
                      {{ goods.goods_title }}
                    </div>
                    <div class="sku sa-flex">
                      <div v-if="goods.goods_sku_text" class="sa-m-r-8">
                        {{ goods.goods_sku_text }}
                      </div>
                      <div>x {{ goods.goods_num }}</div>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                v-if="state.orderDetail.user"
                class="sa-col-16 right"
                :xs="24"
                :sm="24"
                :md="16"
                :lg="16"
                :xl="16"
              >
                <div class="title sa-flex sa-row-between">
                  <template class="sa-flex">
                    物流状态
                    <el-button
                      v-auth="'shop.admin.order.order.updateexpress'"
                      class="is-link sa-m-l-12"
                      type="primary"
                      size="small"
                      @click="onUpdateExpress(ex.id, 'subscribe')"
                      >重新订阅</el-button
                    >
                    <el-popover
                      placement="top"
                      :width="300"
                      trigger="hover"
                      content="如果长时间物流状态没有更新，可以尝试刷新一下。如果没有物流信息，可以尝试重新订阅一下！"
                    >
                      <template #reference>
                        <el-icon class="warning sa-m-l-4">
                          <Warning />
                        </el-icon>
                      </template>
                    </el-popover>
                  </template>
                  <el-button
                    v-auth="'shop.admin.order.order.updateexpress'"
                    class="refresh"
                    size="small"
                    icon="RefreshRight"
                    @click="onUpdateExpress(ex.id, 'search')"
                  ></el-button>
                </div>
                <el-timeline>
                  <el-timeline-item
                    :class="index == 0 ? 'el-timeline-item-first' : ''"
                    v-for="(log, index) in ex.logs"
                    :key="index"
                    :timestamp="log.change_date"
                    :color="index == 0 ? 'var(--t-color-primary)' : ''"
                  >
                    <div class="log-content">
                      {{ log.content }}
                    </div>
                    <div class="change-date sa-m-t-8">{{ log.change_date }}</div>
                  </el-timeline-item>
                </el-timeline>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 商品列表 -->
      <div class="goods-content">
        <el-tabs>
          <el-tab-pane label="商品信息">
            <el-table class="sa-table" :data="state.orderDetail.items" stripe>
              <el-table-column label="商品信息" min-width="250">
                <template #default="scope">
                  <goods-item
                    :goods="{
                      id: scope.row.goods_id,
                      image: scope.row.goods_image,
                      title: scope.row.goods_title,
                      sku_text: scope.row.goods_sku_text,
                    }"
                    :isGoods="true"
                    mode="order-detail"
                  ></goods-item>
                </template>
              </el-table-column>
              <el-table-column prop="goods_price" label="单价(元)" min-width="100" />
              <el-table-column prop="goods_num" label="数量(件)" min-width="80" />
              <el-table-column prop="discount_fee" label="优惠(元)" min-width="90" />
              <el-table-column prop="pay_fee" label="支付金额" min-width="120" />
              <el-table-column label="订单类型" min-width="100">
                <template #default>{{ state.orderDetail.type_text }}</template>
              </el-table-column>
              <el-table-column prop="dispatch_type_text" label="配送方式" width="100">
              </el-table-column>
              <el-table-column label="发货状态" min-width="120">
                <template #default="scope">
                  <status-button
                    from="detail"
                    :order="state.orderDetail"
                    type="dispatch"
                    :item="scope.row"
                  ></status-button>
                </template>
              </el-table-column>
              <el-table-column label="退款状态" min-width="100">
                <template #default="scope">
                  <status-button
                    from="detail"
                    :order="state.orderDetail"
                    type="refund"
                    :item="scope.row"
                    @updateList="getOrderDetail"
                  ></status-button>
                </template>
              </el-table-column>
              <el-table-column label="售后状态" min-width="120">
                <template #default="scope">
                  <status-button from="detail" type="aftersale" :item="scope.row"></status-button>
                </template>
              </el-table-column>
              <el-table-column label="商品评价" min-width="100">
                <template #default="scope">
                  <status-button
                    type="comment"
                    :order="state.orderDetail"
                    :item="scope.row"
                  ></status-button>
                </template>
              </el-table-column>
              <el-table-column width="100" label="配送信息">
                  <template #default="scope">
                      <div v-if="state.orderDetail.dispatch_status!=0">
                          <el-popover trigger="hover" width="220">
                              <div
                                  v-if="scope.row.dispatch_type=='autosend' || scope.row.dispatch_type=='custom'">
                                  <span>发货内容：</span>
                                  <template v-if="scope.row.ext?.dispatch_content_type=='text'">
                                      {{scope.row.ext?.dispatch_content}}
                                  </template>
                                  <template v-if="scope.row.ext?.dispatch_content_type=='params'"
                                      v-for="item in scope.row.ext?.dispatch_content">
                                      {{item.title}}-{{item.content}}
                                  </template>
                              </div>
                              <template v-if="scope.row.dispatch_type!='express'" #reference>
                                  <el-button type="primary" link>查看详情</el-button>
                              </template>
                          </el-popover>
                          <div v-if="scope.row.dispatch_type=='express'">-</div>
                      </div>
                      <div v-else>-</div>
                  </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane v-if="state.orderDetail?.activity_orders?.length > 0" label="优惠信息">
            <el-table class="sa-table" :data="state.orderDetail.activity_orders" stripe>
              <el-table-column prop="id" label="ID" min-width="80" />
              <el-table-column label="活动标题" min-width="120">
                <template #default="scope">
                  <div class="sa-table-line-1">
                    {{ scope.row.activity_title }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="活动类型" min-width="120" align="center">
                <template #default="scope">
                  <div
                    :style="
                      activityStatusStyle(scope.row.activity_type, {
                        padding: '8px 12px',
                        'border-radius': '15px',
                      })
                    "
                  >
                    {{ scope.row.activity_type_text }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="优惠信息" min-width="120" align="center">
                <template #default="scope">
                  <div class="sa-table-line-1">
                    {{ scope.row.discount_text }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="discount_fee"
                label="优惠金额(元)"
                min-width="120"
                align="center"
              />
              <el-table-column
                prop="goods_amount"
                label="参与商品金额(元)"
                min-width="140"
                align="center"
              />
              <el-table-column label="参与商品" min-width="250" align="center">
                <template #default="scope">
                  <el-popover placement="top-start" :width="300" trigger="hover">
                    <div class="discount-goods">
                      <div class="item sa-flex" v-for="goods in scope.row.items" :key="goods">
                        <sa-image :url="goods.goods_image" size="40"></sa-image>
                        <div class="sa-m-l-12">
                          <div class="sa-table-line-1">
                            {{ goods.goods_title }}
                          </div>
                          <div class="">#{{ goods.goods_id }}</div>
                        </div>
                      </div>
                    </div>
                    <template #reference>
                      <div>
                        <span class="discount-items">
                          {{ scope.row.items?.length }}
                        </span>
                        件商品
                      </div>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="参与时间" min-width="172" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 支付列表 -->
      <div class="sa-title">支付信息</div>
      <div class="pay-content">
        <el-table class="sa-table" :data="state.orderDetail.pays" stripe>
          <el-table-column prop="pay_sn" label="支付单号" min-width="250" />
          <el-table-column prop="pay_type_text" label="支付方式" min-width="80" align="center" />
          <el-table-column prop="pay_fee" label="支付金额" min-width="120" align="center" />
          <el-table-column prop="transaction_id" label="交易单号" min-width="280" align="center">
            <template #default="scope">
              <span>{{ scope.row.transaction_id || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="支付状态" min-width="120" align="center">
            <template #default="scope">
              <span :class="['status', `status-${scope.row.status}`]">{{
                scope.row.status_text
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="refund_fee" label="已退款金额" min-width="120" align="center" />
          <el-table-column prop="create_time" label="交易时间" min-width="172" align="center" />
        </el-table>
      </div>
    </el-main>
  </el-container>
</template>
<script setup>
  import { computed, onMounted, reactive, ref, unref } from 'vue';
  import { api } from '../order.service';
  import { api as dataApi } from '@/app/shop/admin/data/data.service';
  import { useModal } from '@/sheep/hooks';
  import useClip from '@/sheep/utils/clipboard.js';
  import useExpress from '@/app/shop/admin/data/express/express.js';

  import StatusButton from './components/status.vue';
  import { activityStatusStyle } from './status.js';
  import GoodsItem from '@/app/shop/components/goods-item.vue';
  import OrderDispatch from './dispatch.vue';
  import OrderRefund from './refund.vue';
  import OrderFee from './fee.vue';
  import StatusSteps from './components/status-steps.vue';
  import InvoiceEdit from '../invoice/edit.vue';
  import { cloneDeep } from 'lodash';

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  const state = reactive({
    orderDetail: {}, // 订单详情
    orderStep: 1,
    orderTabs: '1',
    changeExpressStatus: false, // 变更运单状态
    editConsigneeFlag: false,
    address: {},
    area: [],
  });

  // 获取订单详情
  async function getOrderDetail() {
    const { error, data } = await api.order.detail(props.modal.params.id);
    if (error === 0) {
      state.orderDetail = data;
      state.orderTabs = '1';

      onChangeEditConsigneeFlag(false);
      changeOrderStep();
    }
  }

  async function getArea() {
    const { data } = await dataApi.area.select();
    state.area = data;
  }

  function changeOrderStep() {
    if (state.orderDetail.status == 'unpaid') {
      state.orderStep = 1;
    } else if (state.orderDetail.status == 'paid') {
      state.orderStep = 2;
      switch (state.orderDetail.status_code) {
        case 'nosend':
          state.orderStep = 2;
          break;
        case 'noget':
          state.orderStep = 3;
          break;
        case 'nocomment':
          state.orderStep = 4;
          break;
        case 'commented':
          state.orderStep = 4;
          break;
      }
    } else if (state.orderDetail.status == 'completed') {
      state.orderStep = 5;
    }
  }

  function onOpenDispatch() {
    useModal(
      OrderDispatch,
      {
        title: '订单发货',
        data: state.orderDetail,
      },
      {
        confirm: () => {
          getOrderDetail();
        },
      },
    );
  }

  function onOpenRefund() {
    useModal(
      OrderRefund,
      {
        title: '全部退款',
        class: 'refund-dialog',
        type: 'order.fullRefund',
        data: {
          id: state.orderDetail.id,
          money: state.orderDetail.pay_fee,
        },
      },
      {
        confirm: () => {
          getOrderDetail();
        },
      },
    );
  }

  function onChangeFee() {
    useModal(
      OrderFee,
      {
        title: '改价',
        class: 'fee-dialog',
        id: state.orderDetail.id,
        pay_fee: state.orderDetail.pay_fee,
      },
      {
        confirm: () => {
          getOrderDetail();
        },
      },
    );
  }

  // 备注
  const memoForm = reactive({
    flag: false,
    data: '',
  });
  function onChangeMemoFlag(val) {
    memoForm.flag = true;
    memoForm.data = val;
  }
  async function onConfirmMemo() {
    const { error } = await api.order.editMemo(state.orderDetail.id, {
      memo: memoForm.data,
    });
    if (error == 0) {
      memoForm.flag = false;
      getOrderDetail();
    }
  }

  const { express, deliverCompany, getDeliverCompany, onChangeExpressCode, remoteMethod } =
    useExpress();

  function onChangeExpressStatus(ex) {
    state.changeExpressStatus = true;

    express.name = ex.express_name;
    express.code = ex.express_code;
    express.no = ex.express_no;
  }

  async function onChangeInvoiceStatus(row) {
    useModal(
      InvoiceEdit,
      {
        title: '编辑',
        type: 'edit',
        data: row,
      },
      {
        confirm: () => {
          getOrderDetail();
        },
      },
    );
    // const { data } = await api.invoice.confirm(id);
  }

  // 确认修改运单
  async function onConfirmExpress(order_express_id) {
    await api.order.dispatch({
      order_id: props.modal.params.id,
      order_express_id,
      action: 'change',
      express: express,
    });
    state.changeExpressStatus = false;
    getOrderDetail();
  }

  // 取消运单
  const cancelExpressPopover = ref(false);
  async function onCancelExpress(order_express_id) {
    await api.order.dispatch({
      order_id: props.modal.params.id,
      order_express_id,
      action: 'cancel',
    });
    getOrderDetail();
  }

  async function onUpdateExpress(order_express_id, type) {
    const { error } = await api.order.updateExpress(order_express_id, { type });
    if (error == 0) getOrderDetail();
  }

  // 修改收货信息
  function onChangeEditConsigneeFlag(type) {
    if (state.orderDetail.address) {
      state.address = {
        consignee: state.orderDetail.address.consignee,
        mobile: state.orderDetail.address.mobile,
        pcd: [
          state.orderDetail.address.province_id,
          state.orderDetail.address.city_id,
          state.orderDetail.address.district_id,
        ],
        address: state.orderDetail.address.address,
      };
    }
    state.editConsigneeFlag = type;
  }
  const addressRef = ref();
  async function onEditConsignee() {
    let label = unref(addressRef).getCheckedNodes()[0].pathLabels;
    let tempAddress = cloneDeep(state.address);
    tempAddress = {
      ...tempAddress,
      province_name: label[0],
      province_id: state.address.pcd[0],
      city_name: label[1],
      city_id: state.address.pcd[1],
      district_name: label[2],
      district_id: state.address.pcd[2],
    };
    delete tempAddress.pcd;

    await api.order.editConsignee(state.orderDetail.id, tempAddress);
    getOrderDetail();
    state.editConsigneeFlag = false;
  }

  onMounted(() => {
    getOrderDetail();
    getArea();
  });
</script>
<style lang="scss" scoped>
  .order-detail {
    .warm-tip {
      line-height: 16px;
      font-size: 12px;
      color: var(--sa-font);
    }
    .status-content {
      border-radius: 8px;
      padding: var(--sa-padding);
      background: var(--sa-table-header-bg);
      .left,
      .center,
      .right {
        margin-bottom: var(--sa-padding);
      }
      .right-item {
        line-height: 16px;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        font-size: 12px;
        &.right-item-discount {
          align-items: flex-start;
          margin-bottom: 0;
        }
        .label {
          flex-shrink: 0;
          color: var(--sa-subfont);
        }
        .content {
          color: var(--sa-subtitle);
        }
      }
      .left {
        .name {
          line-height: 24px;
          font-size: 18px;
          color: var(--sa-title);
          font-weight: 900;
          .refresh {
            color: var(--t-color-primary);
            cursor: pointer;
          }
        }
        .desc {
          line-height: 16px;
          font-size: 12px;
          color: var(--sa-subfont);
        }
        .tools {
          height: 32px;
        }
        .memo {
          height: 24px;
          line-height: 24px;
          font-size: 12px;
          font-weight: 400;
          color: var(--sa-font);
        }
      }
      .right {
        .fee-content {
          height: 16px;
          .original-pay-fee {
            color: #999;
          }
        }
      }
      .remark {
        height: 32px;
        line-height: 32px;
        padding: 0 12px;
        background: var(--sa-table-striped);
        border-radius: 4px;
      }
    }
    .tabs-content {
      :deep() {
        .el-tabs {
          .el-tabs__content {
            padding: var(--sa-padding) var(--sa-padding) 0;
          }
        }
      }
      .title {
        height: 24px;
        font-size: 14px;
        font-weight: 600;
        color: var(--sa-title);
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        overflow: hidden;
        .warning {
          color: #faad14;
        }
      }
      .item {
        line-height: 24px;
        margin-bottom: 4px;
        display: flex;
        font-size: 12px;
        &:last-child {
          margin-bottom: 0;
        }
        .label {
          flex-shrink: 0;
          color: var(--sa-subfont);
        }
        .content {
          color: var(--sa-subtitle);
        }
        .copy {
          color: var(--el-color-primary);
        }
      }
      .order-content {
        .el-col {
          padding-bottom: var(--sa-padding);
        }
        .invoice-status {
          font-size: 12px;
          color: var(--sa-font);
        }
        :deep() {
          .nickname {
            height: 24px;
            line-height: 24px;
          }
        }
      }
      .express-content {
        .left {
          padding-bottom: var(--sa-padding);
          max-height: 218px;
          overflow: auto;
          .goods-item {
            .goods-title {
              font-weight: 500;
            }
            .goods-title,
            .sku {
              height: 16px;
              line-height: 16px;
              font-size: 12px;
              color: var(--sa-font);
            }
          }
        }
        .right {
          padding-bottom: var(--sa-padding);
          max-height: 218px;
          overflow: auto;
          .title {
            .refresh {
              padding: 5px;
              background-color: transparent;
            }
          }
          :deep() {
            .el-timeline-item__timestamp {
              position: absolute;
              top: 2px;
              left: -140px;
              margin-top: 0;
            }
          }
        }
      }
    }
    .goods-content {
      border-radius: 8px;
      overflow: hidden;
    }
    .pay-content {
      border-radius: 8px;
      overflow: hidden;
      .status {
        &.status-unpaid {
          color: #999;
        }
        &.status-paid {
          color: #52c41a;
        }
        &.status-refund {
          color: #ff4d4f;
        }
      }
    }
    :deep() {
      .el-tabs {
        .el-tabs__nav-wrap::after {
          height: 0;
        }
        .el-tabs__content {
          background: var(--sa-table-header-bg);
          border-radius: 8px;
        }
      }
    }
    .discount-items {
      color: var(--el-color-primary);
    }

    .discount-goods {
      .item {
        padding: 8px 0;
        border-bottom: 1px solid var(--sa-border);
        &:last-of-type {
          border-bottom: 0;
        }
      }
    }
    .log-content {
      line-height: 18px;
      font-size: 12px;
      font-weight: 400;
      color: var(--sa-subtitle);
    }
    .change-date {
      line-height: 14px;
      font-size: 12px;
      font-weight: 400;
      color: var(--sa-subtitle);
    }
    .el-timeline-item-first {
      &::after {
        content: '';
        position: absolute;
        top: 20px;
        left: 4px;
        width: 2px;
        height: calc(50% - 16px);
        background: var(--t-color-primary);
      }
      .el-timeline-item__tail {
        top: 8px;
        bottom: 8px;
      }
    }
  }
</style>
